<?php
namespace extend;

class Upload{

    private $params = array(
        'max_size'  => 2048000,
        'relative_path'  => '/public/upload',
        'absolute_path'  => ROOT_PATH . 'public' . DS . 'upload',
        'allow_type'    => ['image/jpg', 'image/png', 'image/gif'],
    );

    /**
     * Upload constructor.
     * @param array $params
     */
    function __construct(array $params = array()){
        $this->params = array_merge($this->params, $params);
    }

    /**
     * 检测环境
     */
    function checkDir(){
        $today = date('Ymd');
        !is_dir($this->params['absolute_path']) && mkdir($this->params['absolute_path'], 0777, true);
        $this->params['relative_path'] = "{$this->params['relative_path']}/{$today}";
        $this->params['absolute_path'] = $this->params['absolute_path'] . DS . $today;
        !is_dir($this->params['absolute_path']) && mkdir($this->params['absolute_path'], 0777, true);
    }

    /**
     * 移动文件
     * @param array $name
     * @return array
     * @throws \Exception
     */
    function move(array $name = array()){
        $result = array();
        $this->checkDir();  //检测文件夹是否存在
        $data = $this->checkData($name);
        foreach($data as $key => $item){
            $path_info = pathinfo($item['name']);
            $filename = $this->createFilename($path_info['filename']) . '.' . $path_info['extension'];
            $absolute = $this->params['absolute_path'] . DS . $filename;
            if(!move_uploaded_file($item['tmp_name'], $absolute)){
                throw new \Exception("移动文件{$path_info['filename']}失败!");
            }
            $result[$key] = array(
                'relative'  => "{$this->params['relative_path']}/{$filename}",
                'absolute'  => $this->params['absolute_path'] . DS . $filename
            );
        }
        return $result;
    }

    /**
     * 数据检测
     * @param array $name
     * @return array
     * @throws \Exception
     */
    function checkData(array $name){
        $data = array();
        if(empty($name)){ return $_FILES; }     //如果name为空则获取所有数据
        $diff = array_diff_key(array_flip($name), $_FILES);
        if(!empty($diff)){
            throw new \Exception('没有被上传的文件:' . implode(',', $diff));
        }
        foreach($name as $val){
            $info = $_FILES[$val];
            if($info['size'] > $this->params['max_size']){
                throw new \Exception('上传的文件不能大于' . $this->params['max_size']);
            }
            if(!in_array($info['type'], $this->params['allow_type'])){
                throw new \Exception('不支持的文件类型' . $info['type']);
            }
            $data[$val] = $_FILES[$val];
        }
        return $data;
    }

    /**
     * 创建文件名
     * @param $filename
     * @return string
     */
    function createFilename($filename){
        return md5($filename . uniqid());
    }

}